<template>
  <div class="show-main">
    <el-scrollbar style="height:100%">
      <el-form :inline="true" :model="searchForm" class="demo-form-inline" size="small">
        <el-form-item>
          <el-button type="primary" @click.stop="reload">刷新</el-button>
          <el-button type="primary" @click.stop="add">添加</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="table" border size="small" style="width: 500px;">
        <el-table-column prop="id" label="ID"></el-table-column>
        <el-table-column prop="name" label="分类名称"></el-table-column>
        <el-table-column label="pic" width="125">
          <template slot-scope="scope">
            <el-image style="width: 100px; height: 100px" :src="scope.row.pic" fit="fill" :preview-src-list="[scope.row.pic]"></el-image>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" size="small" @click="edit(scope.row.id)">编辑</el-button>
            <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="page">
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="searchForm.page" :page-sizes="[10,20,30,40]" :page-size="searchForm.limit"
          layout="total, sizes, prev, pager, next, jumper" :total="count">
        </el-pagination>
      </div>
      <el-dialog title="添加商品分类" :visible.sync="addVisible" width="500px" :before-close="handleClose('addForm')">
        <el-form ref="addForm" :model="addForm" label-width="120px" size="small" :rules="rules">
          <el-form-item label="商品分类名称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="分类图片">
            <el-upload ref="addpic" name="image" :action="action" :before-upload="beforeUpload" :on-success="((response, file, fileList)=>{handleSuccess(response, file, fileList,'addpic')})" :on-error="handleError"
              :before-remove="beforeRemove" :file-list="fileList" list-type="picture" :data="imgData" :limit="1" :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('addVisible', 'addForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('addVisible','addForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog title="编辑商品分类" :visible.sync="editVisible" width="500px" :before-close="handleClose('editForm')">
        <el-form ref="editForm" :model="editForm" label-width="120px" size="small" :rules="rules">
          <el-form-item label="商品分类名称" prop="name">
            <el-input v-model="editForm.name"></el-input>
          </el-form-item>
          <el-form-item label="分类图片">
            <el-upload ref="editLogo" name="image" :action="action" :before-upload="beforeUpload" :on-success="((response, file, fileList)=>{handleSuccess(response, file, fileList,'editLogo')})" :on-error="handleError"
              :before-remove="beforeRemove" :file-list="fileList" list-type="picture" :data="imgData" :limit="1" :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
            </el-upload>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="close('editVisible', 'editForm')" size="small">取 消</el-button>
          <el-button type="primary" @click="send('editVisible','editForm')" size="small">确 定</el-button>
        </span>
      </el-dialog>
    </el-scrollbar>
  </div>
</template>
<script>
import { categoryList, delImg, categoryDelete, categoryEdit, categoryInc, categorySave } from '@/network/api.js'

export default {
  name: 'category',
  data () {
    return {
      searchForm: {
        page: 1,
        limit: 10
      },
      count: 0, // 总记录数
      table: [],
      imgData: {}, // 上传图片格外信息
      imgurl: '', // 上传以后图片路径
      fileList: [], // 上传列表
      type: '', // 操作类型 add edit
      action: process.env.NODE_ENV === 'development' ? 'http://dxsd.test.com/school/upload_img' : '/school/upload_img',
      addForm: {
        name: '', // 商品分类名称
        pic: ''// 分类图片
      }, // 添加的表单
      editForm: {
        id: 0,
        name: '', // 商品分类名称
        pic: '' // 分类图片
      }, // 编辑的表单
      addVisible: false, // 添加表单
      editVisible: false, // 编辑表单
      rules: {
        name: [
          { required: true, message: '请输入商品分类名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.search()
  },
  computed: {
  },
  methods: {
    reload () {
      location.reload()
    },
    async search () {
      // 获取分类列表
      try {
        const rtn = await categoryList(this.searchForm)
        this.table = rtn.data.data
        this.count = rtn.data.count
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 每页条数变化
    handleSizeChange (val) {
      this.searchForm.limit = val
      this.search()
    },
    // 当前页变化
    handleCurrentChange (val) {
      this.searchForm.page = val
      this.search()
    },
    // 上传成功
    handleSuccess (response, file, fileList, type) {
      if (response.code !== 200) {
        this.$message.error(response.msg)
        this.$refs[type].clearFiles() // 删除预览
      } else {
        this.imgurl = response.data
      }
    },
    // 上传失败
    handleError () {
      this.$message.error('上传失败')
    },
    // 上传前
    beforeUpload (file) {
      // 判断文件类型
      const imageType = ['image/png', 'image/jpeg', 'image/jpeg']
      if (imageType.indexOf(file.type) === -1) {
        this.$message.error('请上传png|jpg|jpeg图片')
        return false
      }
      this.imgData.token = this.$storage.get('token')
    },
    // 删除前
    async beforeRemove (file, fileList) {
      if (file && file.status === 'success') {
        // 移除方法
        try {
          const formdata = {
            imgurl: this.imgurl,
            type: 4,
            token: this.$storage.get('token')
          }
          if (this.type === 'edit') {
            formdata.id = this.editForm.id
          }
          await delImg(formdata)
          if (this.type === 'edit') {
            this.editForm.pic = ''
          } else {
            this.addForm.pic = ''
          }
          this.imgurl = ''
        } catch (e) {
          this.$message.error(e.message)
          return Promise.reject(new Error(e.message))
        }
      }
    },
    // 超出上传个数
    handleExceed (files, fileList) {
      this.$message.error('已有logo图片请先删除')
    },
    // 添加管理员
    add () {
      this.type = 'add'
      this.addVisible = true
    },
    // 编辑管理员
    async edit (id) {
      try {
        const rtn = await categoryEdit({ id })
        this.type = 'edit'
        this.fileList = []
        this.editVisible = true
        this.$nextTick(() => {
          this.editForm = rtn.data
          if (rtn.data.pic !== '') {
            this.fileList.push({ url: rtn.data.pic })
            this.imgurl = rtn.data.pic
          }
        })
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 删除
    async del (id) {
      try {
        await categoryDelete({ id })
        this.search()
      } catch (e) {
        this.$message.error(e.message)
      }
    },
    // 关闭弹出前操作(不包括取消按钮)
    handleClose (formName) {
      return (done) => {
        this.$refs[formName].resetFields()
        this[formName].pic = ''
        this.imgurl = ''
        this.fileList = []
        done()
      }
    },
    // 取消按钮
    close (visibleName, formName) {
      this.$refs[formName].resetFields()
      this[formName].pic = ''
      this.imgurl = ''
      this.fileList = []
      this[visibleName] = false
    },
    send (visibleName, formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          switch (formName) {
            case 'addForm': // 添加表单
              try {
                this.addForm.pic = this.imgurl
                if (this.addForm.pic === '') {
                  return this.$message.error('请上传分类图片')
                }
                await categoryInc(this.addForm)
                this.close('addVisible', 'addForm')
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
            case 'editForm': // 编辑表单
              try {
                this.editForm.pic = this.imgurl
                if (this.editForm.pic === '') {
                  return this.$message.error('请上传分类图片')
                }
                await categorySave(this.editForm)
                this.close('editVisible', 'editForm')
                this.search()
              } catch (e) {
                this.$message.error(e.message)
              }
              break
          }
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style lang="less">
</style>
